/* eslint-disable no-new,prefer-destructuring */
import ImageCompressor from "image-compressor.js";
import { imgDomain } from "@/configs/env";
import { uploadImg, getUploadToken } from "@/api/common";

export default {
  data() {
    return {
      domain: imgDomain
    }
  },
  methods: {
    async compressAndUpload(file, channel, callback) {
      new ImageCompressor(file, {
        quatity: this.quatity,
        success: (result) => {
          this.upload(result, channel, callback);
        },
        error: (error) => {
          this.$Message.error({ content: error.message, duration: 2 })
        }
      });
    },
    upload(file, channel, callback) {
      console.log("channel", channel)
      if (channel === "qiniu") {
        this.uploadOss(file, callback)
      } else if (channel === "oss") {
        this.uploadOss(file, callback)
      } else if (channel === "server") {
        this.uploadServer(file, callback)
      }
    },
    // 上传阿里云
    async uploadOss(file, callback) {
      const { data } = await getUploadToken()
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const key = `admin/${year}/${month}/${new Date().getTime()}.${file.name ? file.name.split(".")[1] : "jpeg"}`
      const formData = new FormData()
      formData.append("key", key)
      formData.append("OSSAccessKeyId", data.accessKeyId)
      formData.append("policy", data.policy)
      formData.append("signature", data.signature)
      formData.append("success_action_status", "200")
      formData.append("file", file)
      await uploadImg(formData)
      // if (status !== 200) return
      callback(key)
      this.$refs.input.value = ""
    },
    // 上传客户服务器
    async uploadServer(file, callback) {
      const formData = new FormData()
      formData.append("file", file)
      const { data, status } = await uploadImg(formData)
      if (status !== 200) return
      callback(data.scalar)
    }
  }
}
